package com.example.bean;

import java.sql.*;

public class LoginBean {
    private String username;
    private String password;
    private String message;
    private boolean loginResult;

    public LoginBean() {
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean getLoginResult() {
        return loginResult;
    }

    public void setLoginResult(boolean loginResult) {
        this.loginResult = loginResult;
    }


    public void login() {
        if (username == null || username.isEmpty() || password == null || password.isEmpty() )
        {
            this.message = "登录失败：账号或密码为空！";
            this.loginResult = false;
            return;
        }
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/uerinfo?useSSL=false&allowPublicKeyRetrieval=true";
            String user = "root";
            String pass = "123456";
            connection = DriverManager.getConnection(url, user, pass);
            String sql = "SELECT * FROM userInfo WHERE username = ? AND password = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                this.message = "登录成功！";
                this.loginResult = true;
            } else {
                this.message = "登录失败：用户名或密码错误!";
                this.loginResult= false;
            }
        } catch (ClassNotFoundException e) {
            this.message = "登录失败：数据库驱动加载失败";
            this.loginResult = false;

        } catch (SQLException e) {
            this.message = "登录失败：数据库查询错误!";
            this.loginResult= false;
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (SQLException ex) {
                this.message = "登录失败：资源关闭失败!";
                this.loginResult = false;

            }
        }
    }
}